// Created by carolsail

import { ENUM_AUDIO_CLIP, ENUM_UI_TYPE } from "../Enum";
import AudioManager from "../manager/AudioManager";
import DataManager from "../manager/DataManager";
import SdkManager from "../manager/SdkManager";
import ToastManager from "../manager/ToastManager";
import { StaticInstance } from "../StaticInstance";
import { ReactiveAutoSave } from "../Tool/ReactiveAutoSave";
import BaseLayer from "./Baselayer";

const { ccclass, property } = cc._decorator;

@ccclass
export default class MainLayer extends BaseLayer {
  btnPause: cc.Node = null;
  playerNum: cc.Node = null;
  currentLevel: cc.Node = null;
  skills: cc.Node = null;
  skillTip: cc.Node = null;
  private firstClickTime: number = 0; // 记录第一次点击的时间

  onLoad() {
    this.btnPause = this.node.getChildByName("btn_pause");
    this.btnPause.on("click", this.onPauseClick, this);
    this.playerNum = this.node.getChildByName("player_num");
    this.currentLevel = this.node.getChildByName("current_level");
    this.skills = this.node.getChildByName("skills");
    this.skills.children.forEach((skill, index) => {
      if (!skill.hasEventListener("click")) {
        skill.on(
          "click",
          () => {
            this.onSkillClick(index);
          },
          this
        );
      }
    });
    this.skillTip = this.node.getChildByName("skill_tip");
    ReactiveAutoSave.ins.getData().gift == 2
      ? (this.skills.children[1].children[1].active = true)
      : (this.skills.children[1].children[1].active = false);
  }

  onDestroy() {
    this.btnPause.off("click", this.onPauseClick, this);
  }

  onEnable() {
    this.rendorPowerTimer();
  }

  onDisable() {}

  onPauseClick() {
    AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK);
    StaticInstance.uiManager.toggle(ENUM_UI_TYPE.EXIT);
  }

  onSkillClick(index: number) {
    AudioManager.instance.playSound(ENUM_AUDIO_CLIP.CLICK);
    const now = Date.now();
    const wait = 2000; // 0.8秒的等待时间
    if ( now - this.firstClickTime <= wait) {
      return false;
    }
    this.firstClickTime = now;
    // 继续往下运行
    if (index == 1) {
      this.skills.children[1].children[1].active = false;
      ReactiveAutoSave.ins.getData().onGift = true;
    }
    console.log(index + "技能");
    StaticInstance.gameManager.onGameSkill(index);
  }

  setPlayerNum() {
    this.playerNum.getComponent(cc.Label).string = `剩余${
      DataManager.instance.levelPlayerTotal -
      DataManager.instance.levelPlayerClear
    }人`;
  }

  getSkillTip() {
    return this.skillTip.active;
  }

  setSkillTip(bool: boolean) {
    this.skillTip.active = bool;
  }

  setCurrentLevel() {
    this.currentLevel.getComponent(
      cc.Label
    ).string = `第${DataManager.instance.level}关`;
  }
}
